package com.koron.tool.frame;

import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.io.*;

import javax.swing.AbstractAction;
import javax.swing.JFileChooser;
import javax.swing.KeyStroke;
import javax.swing.filechooser.FileNameExtensionFilter;

import com.koron.mybatis.EnvSource;
import com.koron.mybatis.SessionFactory;
import com.koron.tool.MainFrame;

public class SelectDBAction extends AbstractAction {
	private MainFrame frame;

	public SelectDBAction(MainFrame frame) {
		putValue(NAME, "选择本地数据库");
		this.frame = frame;
		putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_MASK + InputEvent.ALT_MASK));
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		JFileChooser chooser = new JFileChooser();
		chooser.addChoosableFileFilter(new FileNameExtensionFilter("本地数据库", "db"));
		chooser.setDialogTitle("先把本地数据库");
		int result = chooser.showDialog(frame, "确定");
		if (result == JFileChooser.APPROVE_OPTION) {
			File f = chooser.getSelectedFile();
			if (!f.exists()) {
				File dir = f.getParentFile();
				if (!dir.exists())
					dir.mkdirs();
				try {
					InputStream ins = getClass().getClassLoader().getResourceAsStream("tool.db");
					FileOutputStream ous = new FileOutputStream(f);
					int i = 0;
					while ((i = ins.read()) != -1)
						ous.write(i);
					ins.close();
					ous.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			MainFrame.localDB.put(SessionFactory.URL, "jdbc:sqlite:/" + f.getAbsolutePath());
			SessionFactory.registeDBMap(EnvSource.DEFAULT, MainFrame.localDB);
		}
	}
}
